<template>
  <div class="cate-container">
    <div class="cate-wrap">
      <div
        v-for="(cate, index) in cates"
        :key="cate.id"
        @click="swicthCate(index)"
        :class="[
          'cate',
          {
            active: index === activeIndex,
          },
        ]"
      >
        {{ cate.name }}
      </div>
    </div>
    <div class="item-wrap">
      <div
        class="item"
        v-for="item in items"
        @click="enterDetail(item.id)"
        :key="item.id"
      >
        <van-card :price="item.minPrice" :title="item.name" :thumb="item.pic">
          <template #footer>
            <van-icon
              class-prefix="icon"
              size="22"
              color="#e93323"
              name="gouwuchetianjia"
            />
          </template>
        </van-card>
      </div>
    </div>
  </div>
  <Tabbar />
</template>

<script setup lang="ts" name="CatePage">
import Tabbar from "@/components/Tabbar.vue";
import { ref, onMounted, watch } from "vue";
import { fetchCates, fetchItems } from "@a/index";
import { useRouter } from "vue-router";
const router = useRouter();
const enterDetail = (id: number) => {
  router.push({
    path: "/detail",
    query: {
      id,
    },
  });
};
const cates = ref<any[]>([]);
const items = ref<any[]>([]);
// 高亮分类的下标
const activeIndex = ref(0);

const getCates = () => {
  fetchCates().then((res) => {
    if (res.data.code === 0) {
      cates.value = res.data.data;
    }
  });
};
watch(
  cates,
  () => {
    getItems();
  },
  {
    deep: true,
  }
);
const getItems = () => {
  fetchItems({
    categoryId: cates.value[activeIndex.value].id,
  }).then((res) => {
    if (res.data.code === 0) {
      items.value = res.data.data.result;
    }
    if (res.data.code === 700) {
      items.value = [];
    }
  });
};
// 点击分类切换高亮状态
const swicthCate = (index: number) => {
  activeIndex.value = index;
  getItems();
};
onMounted(() => {
  getCates();
});
</script>

<style scoped lang="scss">
.cate-container {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 50px;

  display: flex;
  .cate-wrap {
    width: 3rem;
    height: 100%;
    overflow-y: auto;
    border-right: 1px solid #ccc;
    .cate {
      font-size: 14px;
      line-height: 36px;
      text-align: center;
      &.active {
        color: #e93323;
        position: relative;
        background-color: #fafafa;
        &::after {
          content: "";
          position: absolute;
          height: 36px;
          width: 2px;
          background-color: #e93323;
          left: 0;
          top: 0;
        }
      }
    }
  }
  .item-wrap {
    width: 7rem;
    height: 100%;
    overflow-y: auto;
  }
}
</style>
